<template>
  <div class="loginBox">
    <common-bg></common-bg>
    <div class="fixedBox">
      <div class="loginFrom">
        <div style="width: 306px">
          <div class="title">
            <div class="logo">
              <img src="@/assets/imgs/logo_slices/logo.png" />
            </div>
            <div class="nama">Please log in</div>
          </div>
          <el-form
            v-show="!showPhone"
            ref="ruleForm"
            :rules="rules"
            :model="ruleForm"
            label-width="0px"
          >
            <el-form-item prop="phone">
              <el-input
                @keyup.enter.native="submitForm('ruleForm')"
                prefix-icon="iconfont icon-zhanghao7"
                v-model="ruleForm.phone"
                placeholder="请输入登录账号"
                maxlength="11"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                @keyup.enter.native="submitForm('ruleForm')"
                prefix-icon="iconfont icon-mima"
                v-model="ruleForm.password"
                placeholder="请输入密码"
                type="password"
              ></el-input>
            </el-form-item>
            <div class="login-btn">
              <el-button
                type="primary"
                size="medium"
                @click="submitForm('ruleForm')"
                >登录</el-button
              >
            </div>
          </el-form>

          <el-form
            v-show="showPhone"
            :model="ruleFormPhone"
            :rules="rulesPhone"
            ref="ruleFormPhone"
            label-width="0px"
          >
            <el-form-item prop="phone">
              <el-input
                prefix-icon="iconfont icon-shoujihao2"
                v-model="ruleForm.phone"
                placeholder="请输入手机号"
                maxlength="11"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-row :gutter="20">
                <el-col :span="16" style="padding-right: 0">
                  <el-input
                    style="border-radius: 4px 0 0 4px"
                    prefix-icon="iconfont icon-yanzhengma2"
                    v-model="ruleForm.password"
                    placeholder="请输入验证码"
                    type="password"
                  ></el-input>
                </el-col>
                <el-col :span="8">
                  <el-button
                    class="getcode"
                    :class="{ disable: cdTimer }"
                    @click="getCode"
                  >
                    {{ codeBtnTxt }}</el-button
                  >
                </el-col>
              </el-row>
            </el-form-item>
            <div class="login-btn">
              <el-button
                type="primary"
                size="medium"
                @click="submitFormPhone('ruleFormPhone')"
                >登录</el-button
              >
            </div>
          </el-form>
          <div class="bottomBtn">
            <el-button type="text" size="medium" @click="fotgetCode"
              >忘记密码？</el-button
            >
            <el-button type="text" size="medium" @click="switchover">{{
              showPhone == true ? "账号登录" : "手机验证码登录"
            }}</el-button>
          </div>
          <div class="registerBtn">
            <span>暂未账号，</span>
            <el-button
              type="text"
              size="medium"
              @click="dialogFormVisible = true"
              >立即注册</el-button
            >
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      title="请选择公司"
      :visible.sync="dialogData"
      style="margin-top: 18vh"
      width="30%"
    >
      <div class="choice">
        <div v-for="(item, index) in sum" :key="item.id" class="singleChoice">
          <label>
            <input
              type="radio"
              :title="item.title"
              :value="item.id"
              v-model="picked2"
              @change="changeInput(index)"
            />
            <span>{{ item.title }}</span>
          </label>
          <!--  <label :for="item.order">{{ item.title }}</label> -->
        </div>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogFormVisible"
      style="margin-top: 18vh"
      width="30%"
    >
      <div class="dialogBox">
        <div class="title">请选择注册种类</div>
        <div class="select">
          <div class="person" @click="goRegister(0)">
            <div class="icon">
              <div class="img">
                <img src="@/assets/imgs/个人注册.png" />
              </div>
            </div>
            <div class="name">个人注册</div>
          </div>
          <div class="company" @click="goRegister(1)">
            <div class="icon">
              <div class="img">
                <img src="@/assets/imgs/公司名称(1).png" />
              </div>
            </div>
            <div class="name">企业注册</div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from "../../api/login/index";
import { companies, companyId } from "../../api/login/index";
/* import Template from "../Project-archives-management/children/Template.vue"; */
import commonBg from "./components/commonBg.vue";

export default {
  components: {
    commonBg,
    /*  Template, */
  },
  data() {
    return {
      //单选框
      picked2: "",
      /* 当前公司数组 */
      sum: [],
      /* 选择公司蒙尘 */
      dialogData: false,
      /* 登录表单数据（账号加密码） */
      ruleForm: {
        phone: "",
        password: "",
      },
      /* 登录表单失焦判断（账号加密码） */
      rules: {
        phone: [
          {
            required: true,
            message: "请输入登录账号",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
      },
      /* 登录表单数据（手机号加验证码) */
      ruleFormPhone: {
        phone: "",
        password: "",
      },
      /* 登录表单失焦判断（手机号加验证码) */
      rulesPhone: {
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur",
          },
        ],
      },
      /* 防止二次点击 */
      isClick: true,
      /* 判断是账号登录还是手机号登录 */
      showPhone: false,
      /* 是否禁用 */
      cdTimer: null,
      codeBtnTxt: "获取验证码",
      /* 选择注册种类蒙尘 */
      dialogFormVisible: false,
      /* 表单宽度 */
    };
  },
  methods: {
    getCode() {
      /* let self = this;
      self.isValidPhone();
      if (!self.isValidPhoneFlag) return;

      let params = {
        source_type: 1,
        account: self.phone,
        captcha_type: 8,
      };
      self.vaxios.post(`xxxx`, params, (res) => {
        if (res === -1) return;
        self.$toast("验证码已发送");
        self.disabled = true;
        // 设置定时器
        self.createTimer();
      }); */
    },
    //手机号校验
    /*  isValidPhone() {
      var numReg =
        /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1}))+\d{8})$/;
      if (!numReg.test(this.phone)) {
        this.phoneErrorMessage = "请输入正确手机号码";
        this.isValidPhoneFlag = false;
      } else {
        this.phoneErrorMessage = "";
        this.isValidPhoneFlag = true;
      }
    }, */
    //设置定时器
    /* createTimer() {
      let self = this;
      let endTime = new Date(new Date().getTime() + 60 * 1000);

      self.codeBtnTxt = "60s后重新获取";
      self.timer = setInterval(() => {
        let diffTime =
          (Date.parse(new Date(endTime)) - Date.parse(new Date())) / 1000;
        if (diffTime < 0) {
          self.codeBtnTxt = "获取验证码";
          self.disabled = false;
          clearInterval(self.timer);
          self.timer = null;
        } else {
          self.codeBtnTxt = diffTime + "s后重新获取";
          self.disabled = true;
        }
      }, 1000);
    }, */
    /* 账号密码登录确认 */
    submitForm(formName) {
      // 显示loading
      this.$loading();
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 防止二次点击
          if (!this.isClick) return;
          this.isClick = false;
          let send = JSON.parse(JSON.stringify(this.ruleForm));
          api.login(send).then(
            (res) => {
              this.$loading().close();
              console.log(res);
              console.log(res.data.data, "1112");
              if (res && res.data.code == 200) {
                localStorage.setItem("token", res.data.data.token);
                localStorage.setItem("host", res.data.data.host);

                sessionStorage.setItem("useId", res.data.data.id);
                sessionStorage.setItem(
                  "isSupertube",
                  res.data.data.is_super_admin
                );

                this.$message({
                  message: res.data.msg,
                  showClose: true,
                  duration: 3000,
                  type: "success",
                });
                if (res.data.data.is_one_company == 0) {
                  setTimeout(async () => {
                    let res = await companies();
                    console.log(res);
                    if (res && res.data.code == 200) {
                      this.sum = res.data.data.companies;
                    }
                  }, 1000);
                  setTimeout(() => {
                    this.dialogData = true;
                  }, 1000);
                } else if (res.data.data.is_one_company == 1) {
                  setTimeout(() => {
                    this.$router.push("/home");
                    sessionStorage.setItem("companyId", 0);
                  }, 2000);
                }
              } else {
                this.isClick = true;
                this.$message({
                  message: res.data.msg,
                  showClose: true,
                  duration: 3000,
                  type: "error",
                });
              }
            },
            (err) => {
              this.$loading().close();
              this.isClick = true;
            }
          );
        } else {
          console.log("error submit!!");

          return false;
        }
      });
    },
    /* 切换公司 */
    changeInput(index) {
      this.$loading();
      this.sum.map((v, i) => {
        if (i == index) {
          setTimeout(async () => {
            let id = v.id;
            let res = await companyId({ id });
            console.log(res);
            if (res.data.code == 200) {
              this.$message({
                message: res.data.msg,
                showClose: true,
                duration: 3000,
                type: "success",
              });
              this.$loading().close();
              sessionStorage.setItem("companyId", id);
              this.dialogData = false;
              setTimeout(() => {
                this.$router.push("/home");
              }, 2000);
            } else {
              this.$loading().close();
              this.$message({
                message: res.data.msg,
                showClose: true,
                duration: 3000,
                type: "error",
              });
            }
          }, 500);
        } else {
          v.isCheck = false;
        }
      });
    },
    /* 手机号和验证码登录 */
    submitFormPhone(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert(333);
        }
      });
    },
    /* 跳转到忘记密码页面 */
    fotgetCode() {
      this.$router.push({
        path: "/forget",
      });
    },
    /* 判断密码还是验证码 */
    switchover() {
      this.showPhone = !this.showPhone;
      if (this.showPhone) {
        this.$refs["ruleFormPhone"].resetFields();
        this.$refs["ruleForm"].resetFields();
      } else {
        this.$refs["ruleForm"].resetFields();
      }
    },
    /* 跳转到注册页面 */
    goRegister(num) {
      this.$router.push({
        path: "/regist",
        query: {
          type: num,
        },
      });
    },
  },
};
</script>

<style scoped lang="less">
.loginBox {
  width: 100%;
  height: 100%;
  position: relative;
}

.fixedBox {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 9;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loginFrom {
  width: 386px;
  height: 481px;
  background: #ffffff;
  opacity: 1;
  border-radius: 0px;
  display: flex;
  justify-content: center;

  .title {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 64px 0 46px;

    .logo {
      width: 59px;
      height: 59px;
      margin-right: 10px;

      & img {
        width: 100%;
        height: 100%;
      }
    }

    .nama {
      font-size: 30px;
      font-weight: bold;
      color: #3963fd;
      opacity: 1;
    }
  }

  .getcode {
    font-size: 14px;
    font-weight: 400;
    color: #ffffff;
    opacity: 1;
    height: 40px;
    border: none;
    background: #ff9d2d;
    position: relative;
    left: -21px;
    border-radius: 0 3px 3px 0;
  }
  .login-btn {
    text-align: center;
    margin: 43px 0 30px;
  }

  .login-btn button {
    width: 100%;
    height: 48px;
    font-size: 16px;
    background: #3963fd;
    box-shadow: 0px 10px 25px rgba(57, 99, 253, 0.61);
    opacity: 1;
    border-radius: 0px;
  }

  .bottomBtn {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    font-weight: 500;
    color: #000000;
    letter-spacing: 10px;
    opacity: 1;
    margin-bottom: 24px;

    & button {
      padding: 0;
      color: #000;

      &:last-child {
        color: #3963fd;
      }
    }
  }
  .registerBtn {
    font-size: 14px;
    font-weight: 500;
    color: #000000;
    opacity: 1;
    text-align: center;

    & button {
      color: #ff9d2d;
    }
  }
  /deep/.el-input__icon {
    color: #3963fd;
  }
}
.dialogBox {
  margin: 0 auto;
  text-align: center;
  padding: 0 30px;

  .title {
    font-size: 24px;
    font-weight: 500;
    color: #212121;
    opacity: 1;
    margin-bottom: 48px;
  }

  .select {
    display: flex;
    justify-content: space-between;
    & > div {
      cursor: pointer;
    }
    .person {
      .icon {
        background: #ffffff !important;
      }
    }

    .icon {
      width: 140px;
      height: 140px;
      background: #e0e6fc;
      border: 2px solid #e0e6fc;
      border-radius: 50%;
      opacity: 1;
      display: flex;
      justify-content: center;
      align-items: center;

      .img {
        width: 94px;
        height: 94px;

        & img {
          width: 100%;
          height: 100%;
        }
      }
    }
    .name {
      font-size: 16px;
      font-weight: 400;
      color: #000000;
      opacity: 1;
      padding: 18px 0 12px;
    }
  }
}

.choice {
  display: flex;

  justify-content: space-around;
  flex-wrap: wrap;
}
.singleChoice {
  padding: 3px 5px;
  margin: 5px 0;
}
.singleChoice input:checked + span {
  color: #3963fd;

  font-weight: bold;
}
a {
  margin-left: 10px;
}
</style>
